package com.heima.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.user.pojo.ApUser;
import com.heima.model.common.user.userDto.UserDto;
import com.heima.model.common.user.userDto.UserFollowDto;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.UserContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;
    /**
     * 登录
     * @param userDto
     * @return
     */
    @Override
    public ResponseResult login(UserDto userDto) {

    //1.判断登录方式是那种
        if (StringUtils.isNotEmpty(userDto.getPhone())&&StringUtils.isNotEmpty(userDto.getPassword())){
            //2.基于用户名和密码登录
            //2.1 根据用户名查询用户信息
           LambdaQueryWrapper<ApUser> getWrapper = new LambdaQueryWrapper<>();
           getWrapper.eq(ApUser::getPhone,userDto.getPhone());
           getWrapper.eq(ApUser::getStatus,1);
            ApUser apUser = getOne(getWrapper);
            //2.2 判断是否可以查询到
            if (apUser==null){
                //2.3 不能查询到：响应用户名不存在
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //2.4 可以查询到:校验密码
            //2.5 对前端传递的明文密码 + slat---->md5加密--->结果
            String result = DigestUtils.md5DigestAsHex((userDto.getPassword() + apUser.getSalt()).getBytes());
            //2.6 对结果和数据库密文进行比对
            if (!result.equals(apUser.getPassword())){
                //2.7 不相等：密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //2.8 相等：登录成功。生成token响应给前端Long Integer-->long
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            Map<String,Object> map = new HashMap<>();
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user",apUser);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
        //2.游客登录
        String token = AppJwtUtil.getToken(0L);
        Map<String,String> map = new HashMap<>();
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
